package com.sogoodsoft.service.common;

import java.io.File;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sogoodsoft.util.InfosysUtils;
import com.sogoodsoft.web.WebConstants;

public class BackupDBJob {

	private static Logger logger = LoggerFactory.getLogger(BackupDBJob.class);
	private Properties prop;
	private static String name;
	private static String password;
	
	public void execute(){
		if(!isNeed()) return ;
		if(WebConstants.mysql){
			mysql();
		}else{
			oracle();
		}
	}
	
	
	public void mysql(){
		logger.warn("数据库备份任务开始！");
		if(name==null){
			Properties props = InfosysUtils.prop("classes/application.properties");
			 name = props.getProperty("jdbc.username");
		     password = props.getProperty("jdbc.password");
		}
		String path = InfosysUtils.translatePath(WebConstants.DBDIR + File.separator + "sogoodsoft_" + InfosysUtils.weekOfYear() + "_week.sql");
		logger.warn("数据库备份路径："+path);
		String cmd = "mysqldump -u" + name + " -p" + password + " sogoodsoft -r" + path;
		logger.warn("执行备份命令：" + cmd);
		boolean success = false;
	     try {
			success = InfosysUtils.exec(cmd);
			prop.setProperty("WEEK", String.valueOf(InfosysUtils.weekOfYear()));
			InfosysUtils.store(prop, WebConstants.BACKUP_DB_RECORD);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(success)logger.warn("数据库备份成功！");
		logger.warn("数据库备份任务结束！");
	}
	
	
	public void oracle(){
		
		
		logger.warn("数据库备份任务开始！");
		if(name==null){
			Properties props = InfosysUtils.prop("classes/application.properties");
			 name = props.getProperty("jdbc.username");
		     password = props.getProperty("jdbc.password");
		}
		String path = InfosysUtils.translatePath(WebConstants.DBDIR + File.separator + "sogoodsoft_" + InfosysUtils.weekOfYear() + "_week.dmp");
		logger.warn("数据库备份路径："+path);
		String cmd = "exp " + name + "/" + password + " file=" + path;
		logger.warn("执行备份命令：" + cmd);
		boolean success = false;
	     try {
			success = InfosysUtils.exec(cmd);
			prop.setProperty("WEEK", String.valueOf(InfosysUtils.weekOfYear()));
			InfosysUtils.store(prop, WebConstants.BACKUP_DB_RECORD);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(success)logger.warn("数据库备份成功！");
		logger.warn("数据库备份任务结束！");
	}
	
	private boolean isNeed(){
		boolean need = false;
		prop = InfosysUtils.prop(WebConstants.BACKUP_DB_RECORD);
		int last = InfosysUtils.weekOfYear();
		String WEEK = prop.getProperty("WEEK");
		if(WEEK==null)WEEK = "0";
		int week = Integer.parseInt(WEEK);
		if(week!=last){
			need = true;
		}else{
			need = false;
		}
		return need;
	}
	public static void main(String arg[]){
		BackupDBJob job = new BackupDBJob();
		job.mysql();
	}
	
}
